package com.ctgu.computer.utils;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;


public class JwtUtils {

    /**
     * JWT生成
     * @param claims
     * @return
     */
    public static String createJWT( Map<String,Object> claims,String signKey,long expireTime){
        //设置签名算法
        SignatureAlgorithm signatureAlgorithm =SignatureAlgorithm.HS256;
        // 设置过期时间
        long expiredTime = System.currentTimeMillis()+expireTime;
        Date exp = new Date(expiredTime);

        //设置Jwt
        String token = Jwts.builder()
                .setExpiration(new Date(expiredTime))
                .setClaims(claims)
                .signWith(signatureAlgorithm,signKey.getBytes(StandardCharsets.UTF_8))
                .compact();
        return token;
    }

    /**
     * 解析JWT
     * @param jwt
     * @return
     */
    public static Claims parseJwt(String jwt,String signKey){
        Claims body = Jwts.parser()
                .setSigningKey(signKey.getBytes(StandardCharsets.UTF_8))
                .parseClaimsJws(jwt)
                .getBody();
        return body;
    }

}
